<template>
	<view class="addDiet" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar></nav-bar>
		<view class="t-h-container">
			<view class="t-h-title">
				饮食记录
			</view>
			<view class="t-h-sub-title">
				请填写食物信息以记录当前餐别摄入的食物
			</view>
			<view class="f-h">
				<view class="add_f" @click="$u.throttle(pushFood, 1200)">
					<text class="iconfont icon-tianjia"></text>
					<text>添加食物</text>
				</view>
			</view>

			<view class="food" v-for="(item,index) in foodList" :key="index">
				<view class="f_t">
					<text class="t_l">食物{{ index + 1}}</text>
					<text class="iconfont icon-a-shanchu2" v-if="foodList.length > 1"
						@click="$u.throttle(delCurrent(index), 1200)"></text>
				</view>
				<view class="f_container">
					<view class="cell">
						<u-input placeholder="请输入食物名称" color="#545DDE" shape="square" border="none" inputAlign="right"
							v-model="item.foodName">
							<template slot="prefix" class="prefix">
								食物名称
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input shape="square" border="none" readonly inputAlign="right">
							<template slot="prefix" class="prefix">
								<text>图片</text>
							</template>
							<!-- errorIcon="http://oss.antaimedical.com/images/static/2024/06/66764618eb14d0f049f44d23Eu32Tf8eWcBr6c96b6c1ce3f450bfbca58104d6a8b2b.png" -->
							<u-image slot="suffix" :showMenuByLongpress="false" width="40rpx" height="40rpx"
								@click="chooseImage(index)"
								:src="item.picUrl ? item.picUrl : 'http://oss.antaimedical.com/images/static/2024/06/66764618eb14d0f049f44d23Eu32Tf8eWcBr6c96b6c1ce3f450bfbca58104d6a8b2b.png'"
								:lazy-load="true">
							</u-image>

						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="item.heat">
							<template slot="prefix" class="prefix">
								热量
							</template>
							<template slot="suffix" class="suffix ol">
								千卡
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="item.carbohydrate">
							<template slot="prefix" class="prefix">
								碳水化合物
							</template>
							<template slot="suffix" class="suffix">
								克
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="item.protein">
							<template slot="prefix" class="prefix">
								蛋白质
							</template>
							<template slot="suffix" class="suffix">
								克
							</template>
						</u-input>
					</view>
					<view class="cell">
						<u-input placeholder="请填写数值" type="digit" color="#545DDE" placeholderClass="placeholderClass"
							shape="square" border="none" inputAlign="right" v-model="item.fat">
							<template slot="prefix" class="prefix">
								脂肪
							</template>
							<template slot="suffix" class="suffix">
								克
							</template>
						</u-input>
					</view>
				</view>
			</view>
		</view>
		<view class="large_button" :class="{defaultBtn:foodList.length > 1}" @click="$u.throttle(add, 1000)">
			完成
		</view>
	</view>
</template>

<script>
	import {
		addDietaryRecord
	} from '@/api/index.js'
	const dayjs = require('@/utils/dayjs.min.js');

	function createFood() {
		return {
			dietaryTime: '',
			foodName: '',
			type: '',
			userId: '',
			carbohydrate: '',
			fat: '',
			heat: '',
			picUrl: '',
			protein: '',
		}
	}
	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync("userId"),
				time: undefined,
				type: undefined,
				foodList: []
			}
		},
		onLoad(OPTIONS) {
			this.day = OPTIONS.day
			this.time = OPTIONS.time
			this.type = OPTIONS.type
			this.foodList.push(createFood())
		},
		methods: {
			async add() {
				uni.showLoading({
					title: '加载中...'
				})
				let today = this.day.replaceAll('/', '-')
				let body = this.foodList.map(item => {
					item.userId = this.userId
					item.type = this.type
					item.dietaryTime = `${today} ${this.time}:00`
					return item
				})
				let bol = body.every(item => {
					return item.foodName && item.foodName.length > 1
				})
				if (!bol) {
					uni.showToast({
						title: '请填写食物名称',
						icon: 'none'
					})
					return
				}
				try {
					const res = await addDietaryRecord(body)
					uni.hideLoading()
					if (res.code == 200 && res.data) {
						uni.showToast({
							title: '添加成功'
						})
						setTimeout(() => {
							uni.$emit('refreshData')
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			// 选择图片上传
			chooseImage(index) {
				let that = this;
				getApp().globalData.isPriviewApi = true
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success(res) {
						console.log('res', res)
						const src = res.tempFiles[0].tempFilePath;
						that.upload(src, index)
					},
					fail(err) {
						console.log(err)
					}
				});
			},
			upload(src, index) {
				uni.showLoading({
					title: '上传中...'
				})
				uni.uploadFile({ // uploadStaticImg  uploadImages
					url: 'https://antaimedical.com:5000/devicewx-upload/api/v1/upload/AliyunOss/uploadStaticImg',
					header: {
						Authorization: `Bearer ${uni.getStorageSync('token')}`
					},
					filePath: src,
					name: 'file',
					success: async (res) => {
						let obj = JSON.parse(res.data);
						console.log('obj', obj)
						if (obj.code == 200) {
							uni.showToast({
								title: '上传完成'
							})
							this.foodList[index].picUrl = obj.data
						} else {
							uni.showToast({
								title: obj.code,
								icon: 'error',
								duration: 2000
							});
						}
					},
					fail(err) {
						console.log(err)
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			delCurrent(index) {
				this.foodList.splice(index, 1)
			},
			// 添加食物
			pushFood() {
				this.foodList.push(createFood())
			}
		}
	}
</script>


<style lang="scss">
	page {
		min-height: 100%;
	}
</style>
<style lang="scss" scoped>
	.addDiet {
		.f-h {
			margin: 48rpx 0 14rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		.add_f {
			height: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 24rpx;
			border-radius: 22rpx;
			background-color: #545DDE;
			color: #fff;
			font-size: 24rpx;
			line-height: 44rpx;

			.iconfont {
				font-size: 20rpx;
				padding-right: 8rpx;
			}
		}

		.food {
			width: 100%;
			margin-bottom: 48rpx;

			.f_t {
				display: flex;
				align-items: center;

				.t_l {
					font-size: 28rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					padding-left: 16rpx;
				}

				.icon-a-shanchu2 {
					font-size: 44rpx;
					color: #FA5151;
					padding-left: 16rpx;
				}

			}

		}

		.defaultBtn {
			position: relative;
		}

		.large_button {
			position: fixed;
			bottom: 76rpx;
			left: 50%;
			transform: translateX(-50%);
		}
	}
</style>